import React from 'react'
import { connect } from 'react-redux'
import { messages } from "share/common"
import { Form, Radio, Icon, Row, Col, Button, Tabs, Badge, Popconfirm, message } from 'antd'
import SlideFrame from  'components/slide-frame'
const { TabPane } = Tabs;
import "styles/setting/workflow-config/workflow-config.scss"
import NewWorkFlowConfig from 'containers/application-setting/new-fp-setting'
import WorkFlowConfigDefault from 'containers/application-setting/default-fp-setting'
import workflowConfigData from 'containers/setting/workflow-config/work-flow-config-data'
import workflowConfigService from 'containers/setting/workflow-config/workflow-config.service'
import AdvancedTable from 'components/advanced-table'
const RadioGroup = Radio.Group;
const SimpleTable = AdvancedTable.SimpleTable;
import errorMessage from "share/errorMessage";
import Priority from 'components/template/priority'
import Info from 'components/info'
const options = [
  { label: messages('common.all')/*全部*/, value: 'ALL' },
  { label: messages('request-4.key553')/*租户*/, value: 'TENANT' },
  { label: messages('request-4.key12')/*公司*/, value: 'COMPANY' },
];
const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};
class WorkflowConfig extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      nowKey: 'workflow-action',
      slideShow: false,
      title: '',
      nowMode: 'create',
      nowConfig: [],
      tableConfig: {
        columns: [{
          dataIndex: 'levelCode', title: messages('request-4.key554')/*层级*/,
          render: (text) => {
            return <span>
              {text === 'COMPANY' ? messages('request-4.key12')/*公司*/ : messages('request-4.key553')/*租户*/}</span>
          }
        }, {
          dataIndex: 'levelOrgName', title: messages('request-4.key555')/*所属组织*/,
          render: (text) => text || '-'
        }, {
          dataIndex: 'enabled', title: messages('common.column.status')/*状态*/,
          render: (text) => {
            return <span>
            <Badge status={text ? "success" : 'error'}/>
              {text ? messages('common.status.enable')/*启用*/ : messages('request-4.key227')/*禁用temp*/}</span>
          }
        }, {
          title: messages('common.operation')/*操作*/,
          dataIndex: 'delete',
          render: (value, record) =>
          !record.readOnly && <Popconfirm
            placement="bottomRight"
            title={messages('request-4.key556')/*您确定删除这条规则吗？*/}
            onConfirm={e => this.handleDelete(e, record)}
          >
            <a
              onClick={e => {
                e.preventDefault();
                e.stopPropagation()
              }}>
              {messages('common.delete')/*删除*/}
            </a>
          </Popconfirm>
        },],
        searchForm: [
          {
            id: 'levelCode',
            initialValue: 'ALL',
            label: messages('request-4.key554')/*层级*/,
            component: <RadioGroup options={options} initialValue="ALL"/>,
            tagParser: value => this.getLevelTypeValue(value),
            dataIndex: 'levelCode',
          }, {
            id: 'levelOrgId',
            dataIndex: 'levelOrgName',
            label: messages('request-4.key555')/*所属组织*/,
            parser: value => ({ levelOrgId: value ? value.rangeValue.id : null }),
            tagParser: value => value && value.rangeValue.name,
            component: <Priority
              style={{ marginLeft: 0 }}
              formItemLayout={formItemLayout}
              top='TENANT'
              onlyCompany
              showCompanyComponent={false}
              showCompany
              companyProps={{
                single: true
              }}
            />,
          }
        ],
      }
    }
  }

  componentDidMount() {
    let { nowKey } = this.state;
    this.setState({
      nowConfig: workflowConfigData[nowKey].configs
    })
  }

  getLevelTypeValue(type) {
    let text = messages('common.all')/*全部*/;
    switch(type) {
      case 'TENANT':
        text = messages('request-4.key553')/*租户*/;
        break;
      case 'COMPANY':
        text = messages('request-4.key12')/*公司*/;
        break;
    }
    return text;
  }

  callback = e => {
    let { nowKey } = this.state;
    this.setState({ nowKey: e, nowConfig: workflowConfigData[nowKey].configs }, () => {
      this.advancedTableRef.getList();
    })
  };

  afterCloseSlideFrame = flag => {
    if (flag) {
      this.advancedTableRef.getList();
    }
  };

  handleDelete = (e, record) => {
    e.stopPropagation();
    const { nowKey } = this.state;
    let apiObj = {
      'workflow-action': workflowConfigService.deleteActionConfig,
      'workflow-control': workflowConfigService.deleteControlConfig,
      'agency-setting': workflowConfigService.deleteProxyConfig
    };
    let paramsKey = {
      'workflow-action': 'id',
      'workflow-control': 'id',
      'agency-setting': 'id'
    }
    apiObj[nowKey]({ [paramsKey[nowKey]]: record[paramsKey[nowKey]] })
      .then(res => {
        this.advancedTableRef.getList();
      }).catch(e => {
      errorMessage(e.response)
    })
  };

  service = (page, size, searchParams, extraParams) => {
    const { nowKey } = this.state;
    let apiObj = {
      'workflow-action': workflowConfigService.getActionConfigList,
      'workflow-control': workflowConfigService.getControlConfigList,
      'agency-setting': workflowConfigService.getProxyConfigList
    };
    if (searchParams.levelCode === 'ALL') {
      searchParams.levelCode = ''
    }
    return apiObj[nowKey]({ page, size, ...searchParams })
  };

  handleCreate = (title, nowMode, id = null) => {
    const { nowKey } = this.state;
    let pageFile = NewWorkFlowConfig, apiService = '', saveApiService = '';
    //配置接口
    let apiObj = {
      'workflow-action': {
        apiService: workflowConfigService.getActionDefaultConfig,//默认值接口
        editApiService: workflowConfigService.getActionConfigDetail,//详情接口
        saveApiService: workflowConfigService.postActionConfig,//保存接口
      },
      'workflow-control': {
        apiService: workflowConfigService.getControlDefaultConfig,
        editApiService: workflowConfigService.getControlConfigDetail,
        saveApiService: workflowConfigService.postControlConfig,
      },
      'agency-setting': {
        apiService: workflowConfigService.getProxyDefaultConfig,
        editApiService: workflowConfigService.getProxyConfigDetail,
        saveApiService: workflowConfigService.postProxyConfig,
      }
    };
    switch(nowMode) {
      case 'create':
        pageFile = NewWorkFlowConfig;
        apiService = apiObj[nowKey].apiService;
        saveApiService = apiObj[nowKey].saveApiService;
        break;
      case 'default':
        pageFile = WorkFlowConfigDefault;
        apiService = apiObj[nowKey].apiService;
        break;
      case 'edit':
        pageFile = NewWorkFlowConfig;
        apiService = apiObj[nowKey].editApiService;
        saveApiService = apiObj[nowKey].saveApiService;
        break;
    }
    SlideFrame.open({
      title: title,
      content: pageFile,
      afterClose: this.afterCloseSlideFrame,
      width: '800px',
      params: {
        id,
        apiService,
        saveApiService,
        configFp: workflowConfigData[nowKey].configs,
      }
    }, this)
  };

  render() {
    const { nowKey, tableConfig } = this.state;
    const infoData = {
      dataSource: { explain: workflowConfigData[nowKey].description },
      attributes: [{ title: messages('expense-8.key6')/*说明*/, dataIndex: 'explain', span: 24 }]
    };
    const attributes = infoData && infoData.attributes && infoData.attributes.map(i => {i.widthFix = false; return i;});
    return (
      <div className='workflow-config full-height-page full-page-margin'>
        <Tabs defaultActiveKey="1" onChange={this.callback}>
          <TabPane tab={messages('request-4.key557')/*审批流功能设置*/} key="workflow-action">
          </TabPane>
          <TabPane tab={messages('request-4.key558')/*审批流管控设置*/} key="workflow-control">
          </TabPane>
          <TabPane tab={messages('request-4.key559')/*代理设置*/} key="agency-setting">
          </TabPane>
        </Tabs>
        <SimpleTable
          onRef={ref => this.advancedTableRef = ref}
          style={{ marginTop: 10 }}
          {...tableConfig}
          onRow={record => ({
            onClick: () => this.handleCreate('编辑', 'edit', record.id)
          })}
          rowKey="id"
          onGetDataError={e => errorMessage(e.response)}
          service={this.service}
        >
          {infoData && <Info paragraph
                        dataSource={infoData.dataSource}
                        attributes={attributes}/>
          }
          <Row type="flex" className="table-header-buttons" justify="space-between" align="middle">
            <Col span={12}>
              <Button
                type="primary"
                onClick={() => this.handleCreate(messages('common.create')/*新建*/, 'create')}>
                {messages('common.create')/*新建*/}
              </Button>
            </Col>
            <Col span={12} className={'default-btn'}>
              <div className="default-btn-text" onClick={() => this.handleCreate(messages('request-4.key561')/*默认规则*/, 'default')}>
                <Icon type="file-text" style={{ marginRight: 5 }}/>{messages('request-4.key561')/*默认规则*/}
              </div>
            </Col>
          </Row>
        </SimpleTable>
      </div>
    )
  }
}

WorkflowConfig.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company,
    language: state.main.language,
  }
}

const wrappedWorkflowConfig = Form.create()(WorkflowConfig);

export default connect(mapStateToProps)(wrappedWorkflowConfig)
